/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.aliyun.opensearch.object;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.json.JSONObject;
import org.json.JSONArray;

import com.aliyun.opensearch.CloudsearchDoc;

/**
 * 一个文档对应的数据
 * 
 * @author 童昭 liushuang.ls@alibaba-inc.com
 * @createDate 2013-12-20
 */
public class SingleDoc {
    private String cmd;
    private Map<String, String> fields = new HashMap<String, String>();

    /**
     * 添加一个属性值
     * 
     * @param key key
     * @param value value
     */
    public void addField(String key, String value) {
        if (value.contains(CloudsearchDoc.HA_DOC_MULTI_VALUE_SEPARATOR)) {
            String[] values = value.split(CloudsearchDoc.HA_DOC_MULTI_VALUE_SEPARATOR);
            JSONArray array = new JSONArray();
            for (String v : values) {
                array.put(v);
            }
            this.fields.put(key, array.toString());
        } else {
            this.fields.put(key, value);
        }
    }

    public String getCmd() {
        return cmd;
    }

    public void setCmd(String cmd) {
        this.cmd = cmd;
    }

    public Map<String, String> getFields() {
        return fields;
    }

    /**
     * 获取一条记录的JSON格式
     * 
     * @return 一条记录的JSON格式
     */
    public JSONObject getJSONObject() {
        JSONObject json = new JSONObject();
        try {
            json.put("cmd", cmd);
            JSONObject jsonFields = new JSONObject();
            for (Entry<String, String> entry : fields.entrySet()) {
                jsonFields.put(entry.getKey(), entry.getValue());
            }
            json.put("fields", jsonFields);
        } catch (Exception e) {
            // ignore
        }
        return json;
    }
}
